package com.xmsx.back.controller.admin;

import com.xmsx.back.pojo.User;
import com.xmsx.back.results.Result;
import com.xmsx.back.service.admin.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin")
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(@RequestParam("username") String username, @RequestParam("password") String password) {
        return userService.login(username, password);
    }

    /**
     * 新建管理员
     *
     * @param username
     * @param password
     * @return
     */
    @PutMapping("/admin")
    public Result<String> register(@RequestParam("username") String username,
                                   @RequestParam("password") String password) {

        User user = userService.getByUserName(username);

        if (null != user) {
            // 用户名已经存在，报错
            return Result.error("用户名已经存在");
        }

        user = new User();
        user.setUsername(username);
        user.setPassword(password);

        userService.setUser(user);
        return Result.success("注册成功！");
    }

    /**
     * 删除管理员
     *
     * @param username
     * @return
     */
    @DeleteMapping("/admin")
    public Result<String> deleteUser(@RequestParam("username") String username){
        User user = userService.getByUserName(username);
        if (null == user) {
            // 用户名不存在，无法删除
            return Result.error("用户名不存在，删除失败");
        }
        userService.dropUserByUsername(username);
        return Result.success("删除成功！");
    }

    /**
     * 获取所有管理员
     *
     * @return
     */
    @GetMapping("/adminList")
    public Result<List<User>> allUsers() {
        return Result.success(userService.getAllUsers());
    }

    /**
     * 修改管理员密码
     * @param username
     * @param password
     * @param newPassword
     * @return
     */
    @PostMapping("/admin")
    public Result<String> alter(@RequestParam("username") String username,
                                   @RequestParam("password") String password,@RequestParam("newPassword") String newPassword) {


        return userService.alter(username,password,newPassword);
    }

}
